<template>
  <div class="amap-search">
    <el-autocomplete
      ref="autoComplete"
      v-model="keyword"
      :fetch-suggestions="querySearchAsync"
      :trigger-on-focus="false"
      :placeholder="getPlaceholder()"
      @select="handleSelect"
      @keyup.enter.native="handleSearch"
      size="small"
      clearable
      :disabled="disabled"
      class="search-input"
      :popper-class="'amap-search-suggestions'">
      <template slot="prefix">
        <i class="el-icon-location-information"></i>
      </template>
      <el-button
        slot="append"
        icon="el-icon-search"
        @click="handleSearch"
        :disabled="disabled">
        搜索
      </el-button>
      <template slot-scope="{ item }">
        <div class="suggestion-item">
          <div class="name">
            <i class="el-icon-location-outline"></i>
            {{ item.name }}
          </div>
          <div class="address">
            <i class="el-icon-map-location"></i>
            {{ item.address || item.district || '暂无详细地址' }}
          </div>
        </div>
      </template>
    </el-autocomplete>
  </div>
</template>

<script>
export default {
  name: 'AMapSearch',
  props: {
    value: {
      type: String,
      default: ''
    },
    city: {
      type: String,
      default: ''
    },
    webServiceKey: {
      type: String,
      required: true
    },
    region: {
      type: Object,
      default: () => ({})
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      keyword: this.value,
      requestCount: 0,
      poiCache: {}
    }
  },
  computed: {
    currentRegion() {
      const { provinceName, cityName, districtName } = this.region;
      if (!provinceName) return '';
      let region = provinceName;
      if (cityName && cityName !== '市辖区') region += cityName;
      if (districtName) region += districtName;
      return region;
    }
  },
  watch: {
    value(val) {
      this.keyword = val;
    },
    disabled(val) {
      if (val) {
        this.clear();
      }
    }
  },
  methods: {
    getPlaceholder() {
      if (this.disabled) {
        return '请先选择省市区';
      }

      const { provinceName, cityName, districtName } = this.region;
      if (districtName) {
        return `在${districtName}区域内搜索医院、诊所等`;
      } else if (cityName && cityName !== '市辖区') {
        return `在${cityName}区域内搜索医院、诊所等`;
      } else if (provinceName) {
        return `在${provinceName}区域内搜索医院、诊所等`;
      } else {
        return '请输入地址搜索，例如：北京协和医院';
      }
    },

    querySearchAsync(keyword, cb) {
      if (this.disabled || !keyword) {
        cb([]);
        return;
      }

      if (!this.currentRegion) {
        this.$message.warning('请先选择省市区');
        cb([]);
        return;
      }

      const requestId = ++this.requestCount;
      console.log(`发起搜索请求 '': ${keyword}, 区域:'', Key: ''`);

      if (this.poiCache[keyword]) {
        console.log(`使用缓存结果 requestId: ${keyword}`);
        cb(this.poiCache[keyword]);
        return;
      }


      let cityParam = '';

      if (this.region.districtName) {
      } else if (this.region.cityName && this.region.cityName !== '市辖区') {

      } else if (this.region.provinceName) {
      }

      const params = {
        key: this.webServiceKey,
        keywords: keyword,
        type: '',
        city: cityParam,
        citylimit: 'true',
        output: 'json',
        datatype: 'all',
        extensions: 'all',
        offset: 25,
        page: 1
      };

      // 构建查询字符串
      const queryString = Object.keys(params)
        .filter(key => params[key] !== '')
        .map(key => `${key}=${encodeURIComponent(params[key])}`)
        .join('&');

      // 发起搜索请求
      fetch(``)
        .then(response => {
          if (!response.ok) {
          }
          return response.json();
        })
        .then(result => {
          if (requestId !== this.requestCount) {
            return;
          }

          if (result.status === '1' && result.pois && result.pois.length > 0) {
            const tips = result.pois
              .filter(item => {
                const isHealthcare =
                  item.name.includes('学校') ||
                  item.name.includes('ktv') ||
                  item.name.includes('生活') ||
                  item.name.includes('足疗') ||
                  (item.type && item.type.includes('w'));

                if (this.region.districtName) {
                  return isHealthcare && item.adname && (
                    item.adname.includes(this.region.districtName) ||
                    this.region.districtName.includes(item.adname) ||
                    item.adname.includes(this.region.districtName.substring(0, 2))
                  );
                }
                // 对于市级搜索
                else if (this.region.cityName && this.region.cityName !== '市辖区') {
                  return isHealthcare && (
                    item.cityname && (item.cityname.includes(this.region) ||
                                     this.region.cityName.includes(item.cityname))
                  );
                }
                else {
                  return isHealthcare && item.pname && (
                    item.pname.includes(this.region.provinceName) ||
                    this.region.provinceName.includes(item.pname)
                  );
                }
              })


            this.poiCache[keyword] = tips;


            cb(tips);
          }
        })
        .catch(error => {
          this.$message.error('搜索服务异常，请稍后重试');
          cb([]);
        });
    },

    handleSelect(item) {
      if (this.disabled) return;
      this.$emit('input', item.name);
      this.$emit('select', item);
    },

    handleSearch() {
      if (this.disabled) {
        this.$message.warning('请先选择省市区');
        return;
      }

      if (!this.keyword) {
        this.$message.warning('请输入搜索关键词');
        return;
      }

      this.$emit('search', this.keyword);
    },

    clear() {
      this.keyword = '';
      this.$emit('input', '');
      this.requestCount = 0;
      this.poiCache = {};
      this.$emit('clear');
    }
  }
}
</script>

<style lang="scss">
.amap-search-suggestions {
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 6px 0;

  .el-scrollbar__view {
    padding: 0 !important;
  }

  li {
    line-height: 1.5;
    padding: 0 !important;
  }
}
</style>

<style lang="scss" scoped>
.amap-search {
  width: 100%;
  position: relative;

  .search-input {
    width: 100%;

    :deep(.el-input__inner) {
      border-radius: 4px;
      height: 36px;
      font-size: 14px;
    }

    :deep(.el-input__prefix) {
      color: #409EFF;
    }

    :deep(.el-input-group__append) {
      background-color: #409EFF;
      border-color: #409EFF;
      padding: 0 15px;

      .el-button {
        border: 0;
        margin: 0;
        color: #fff;
        padding: 0;
        background: transparent;
        font-size: 13px;

        &:hover:not(:disabled) {
          color: #fff;
          opacity: 0.9;
        }

        &:disabled {
          color: #C0C4CC;
          cursor: not-allowed;
        }
      }

      &.is-disabled {
        background-color: #F5F7FA;
        border-color: #DCDFE6;
      }
    }

    :deep(.el-input__inner) {
      border-right: 0;

      &:disabled {
        background-color: #F5F7FA;
        border-color: #E4E7ED;
        color: #C0C4CC;
      }
    }
  }
}

.suggestion-item {
  padding: 8px 12px;
  cursor: pointer;
  transition: background-color 0.2s;
  border-bottom: 1px solid #f0f0f0;

  &:hover {
    background-color: #f5f7fa;
  }

  &:last-child {
    border-bottom: none;
  }

  .name {
    font-size: 14px;
    color: #303133;
    font-weight: 500;
    margin-bottom: 4px;

    i {
      color: #409EFF;
      margin-right: 6px;
    }
  }

  .address {
    font-size: 12px;
    color: #909399;
    white-space: normal;
    line-height: 1.4;

    i {
      font-size: 12px;
      color: #C0C4CC;
      margin-right: 4px;
    }
  }
}
</style>
